#include "S_KEYBORAD.h"

static uint8_t keysta[18][8] = {0}; //记录按键扫描情况,18个按键每个按键采样8次
static uint32_t keyval = 0;//使用32位数来储存18个按键的情况

//记录几个按键引脚的编号
uint16_t __PinNumIn[4] = {KEY_Y1_Pin, KEY_Y2_Pin, KEY_Y3_Pin, KEY_Y4_Pin};
GPIO_TypeDef *__PinPortIn[4] = {KEY_Y1_GPIO_Port, KEY_Y2_GPIO_Port, KEY_Y3_GPIO_Port, KEY_Y4_GPIO_Port};
uint16_t __PinNumOut[4] = {KEY_X1_Pin, KEY_X2_Pin, KEY_X3_Pin, KEY_X4_Pin};
GPIO_TypeDef *__PinPortOut[4] = {KEY_X1_GPIO_Port, KEY_X2_GPIO_Port, KEY_X3_GPIO_Port, KEY_X4_GPIO_Port};

void keyboradscan(void)
{
    static uint8_t i = 0;
    uint32_t __keyval = 0;

    for (int j = 0; j < 4; j++)//按序读取按键值
    {
        HAL_GPIO_WritePin(__PinPortOut[j], __PinNumOut[j], GPIO_PIN_SET);
        for (int k = 0; k < 4; k++)
            keysta[j + k * 4][i] = HAL_GPIO_ReadPin(__PinPortIn[k], __PinNumIn[k]);
        HAL_GPIO_WritePin(__PinPortOut[j], __PinNumOut[j], GPIO_PIN_RESET);
    }

    keysta[16][i] = !HAL_GPIO_ReadPin(UserKey1_GPIO_Port, UserKey1_Pin);//两个独立的按键
    keysta[17][i] = !HAL_GPIO_ReadPin(UserKey2_GPIO_Port, UserKey2_Pin);

    i++;
    if (i == 8)
        i = 0;

    for (int j = 0; j < 18; j++)
    {
        uint8_t sum = 0;
        for (int k = 0; k < 8; k++)
            sum += keysta[j][k];
        if (sum == 8)
            __keyval += 1 << j;
    }
    keyval = __keyval;
}

uint8_t keynumadjust(uint8_t keynum)//把检测到的按键顺序调整一下(都是原理图的锅导致牛头不对马嘴
{
    if (keynum <= 4)
        return keynum + 12;
    if (keynum <= 8)
        return keynum + 4;
    if (keynum <= 12)
        return keynum - 4;
    if (keynum <= 16)
        return keynum - 12;
    return keynum;
}

uint8_t GetKeyVal(uint8_t keynum)
{
    if (keyval & (1 << (keynumadjust(keynum) - 1)))//如果该按键按下则返回1
        return 1;
    return 0;
}
